package com.egu.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.egu.mapper.CustomerTypeMapper;
import com.egu.model.CustomerType;
import com.egu.model.CustomerTypeExample;
import com.egu.model.CustomerTypeExample.Criteria;
import com.egu.service.CustomerTypeService;
import com.egu.vo.PageParam;
import com.egu.vo.RequestPageVo;
import com.egu.vo.RequestResultVo;

@Service
public class CustomerTypeServiceImple implements CustomerTypeService {

	@Autowired
	CustomerTypeMapper customerTypeMapper;

	public RequestPageVo<CustomerType> getList(PageParam param, CustomerType customerType) {
		RequestPageVo<CustomerType> result = new RequestPageVo<CustomerType>();
		CustomerTypeExample example = new CustomerTypeExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsUsedEqualTo("1");
		if (StringUtils.isNotBlank(customerType.getTypeName())) {
			criteria.andTypeNameLike("%" + customerType.getTypeName() + "%");
		}
		int count = (int) customerTypeMapper.countByExample(example);
		if (count > 0) {
			example.setStartPage(param.getOffset());
			example.setPageSize(param.getLimit());
			List<CustomerType> list = customerTypeMapper.selectByExample(example);
			result.setRows(list);
			result.setTotal(count);
		}
		return result;
	}

	@Override
	public RequestResultVo<List<CustomerType>> getAllList() {
		CustomerTypeExample example = new CustomerTypeExample();
		example.createCriteria().andIsUsedEqualTo("1");
		List<CustomerType> list = customerTypeMapper.selectByExample(example);
		return RequestResultVo.success(list);
	}

	@Override
	@Transactional
	public RequestResultVo<CustomerType> saveOrUpdate(CustomerType customerType) {
		if (customerType.getId() == null) {
			customerTypeMapper.insertSelective(customerType);
		} else {
			customerTypeMapper.updateByPrimaryKeySelective(customerType);
		}
		return RequestResultVo.success();
	}

	@Override
	@Transactional
	public RequestResultVo<CustomerType> deleteDataById(Integer id) {
		CustomerType customerType = new CustomerType();
		customerType.setId(id);
		customerType.setIsUsed("0");
		try {
			customerTypeMapper.updateByPrimaryKeySelective(customerType);
		} catch (Exception e) {
			return RequestResultVo.error("数据库删除失败");
		}
		return RequestResultVo.success();
	}

}
